package cn.lu.train.net;


import cn.lu.train.api.API;
import cn.lu.train.net.interceptor.DynamicHostInterceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by luxianyue on 2018/3/12.
 */

public class NetUtils {
    private static volatile NetUtils instance;
    private Retrofit mRetrofit;
    private boolean log = true;

    private NetUtils(){}

    public static NetUtils get() {
        if (instance == null) {
            synchronized (NetUtils.class) {
                if (instance == null) {
                    instance = new NetUtils();
                }
            }
        }
        return instance;
    }

    public Retrofit retrofit() {
        if (mRetrofit == null) {
            mRetrofit = new Retrofit.Builder()
                    .baseUrl(API.baseUrl)
                    .client(createClient())
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
        }
        return mRetrofit;
    }

    public Retrofit.Builder retrofitBuilder() {
        return new Retrofit.Builder().baseUrl(API.baseUrl);
    }

    public Retrofit.Builder retrofitBuilder(String baseUrl) {
        return new Retrofit.Builder().baseUrl(baseUrl);
    }

    private OkHttpClient createClient() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(log ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);
        return new OkHttpClient.Builder()
                .addInterceptor(new DynamicHostInterceptor())
                .addInterceptor(interceptor)
                .build();
    }
}
